<template>
    <div class="detail-page">
        <el-page-header content="调拨单详情" @back="handleClose" class="detail-header" />

        <el-card class="detail-card info-card" shadow="never">
            <div class="header-section">
                <div class="title-area">
                    <span class="order-label">调拨单号:</span>
                    <span class="order-number">{{ transferForm.transferNo || '--' }}</span>
                    <el-tag :type="getStatusTagType(transferForm.transferStatus)" size="default" class="status-tag">
                        {{ getStatusText(transferForm.transferStatus) }}
                    </el-tag>
                </div>
                <div class="action-buttons">
                    <el-button type="primary" @click="handleTransferOut" size="small">调出</el-button>
                    <el-button @click="handleCopy" size="small">复制</el-button>
                    <el-button @click="handlePrint" size="small">打印</el-button>
                </div>
            </div>

            <div class="status-info">
                <div class="status-item">
                    <span class="status-label">出库状态:</span>
                    <el-tag :type="getOutboundStatusTagType(transferForm.outboundStatus)" size="small">
                        {{ getOutboundStatusText(transferForm.outboundStatus) }}
                    </el-tag>
                    <span class="status-count">{{ transferForm.outboundQuantity || 0 }}/{{ transferForm.transferQuantity || 0 }}</span>
                </div>
                <div class="status-item">
                    <span class="status-label">入库状态:</span>
                    <el-tag :type="getInboundStatusTagType(transferForm.inboundStatus)" size="small">
                        {{ getInboundStatusText(transferForm.inboundStatus) }}
                    </el-tag>
                    <span class="status-count">{{ transferForm.inboundQuantity || 0 }}/{{ transferForm.transferQuantity || 0 }}</span>
                </div>
            </div>

            <div class="info-content">
                <el-descriptions :column="4" border>
                    <el-descriptions-item label="制单人">
                        <span class="info-value">{{ transferForm.maker || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="所在部门">
                        <span class="info-value">{{ transferForm.department || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="制单时间">
                        <span class="info-value">{{ formatDateTime(transferForm.makerTime) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="调拨类型">
                        <span class="info-value">{{ transferForm.transferType || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="调拨申请日期">
                        <span class="info-value">{{ formatDate(transferForm.transferApplicationDate) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="调出仓库">
                        <span class="info-value">{{ transferForm.outboundWarehouseName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="调入仓库">
                        <span class="info-value">{{ transferForm.inboundWarehouseName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="经办人">
                        <span class="info-value">{{ transferForm.handler || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="备注" :span="4">
                        <span class="info-value">{{ transferForm.remark || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-card>

        <el-card class="detail-card tabs-card" shadow="never">
            <div class="tabs-section">
                <el-tabs v-model="activeTab" type="card" class="detail-tabs" @tab-change="handleTabChange">
                    <el-tab-pane label="其他信息" name="other">
                        <div class="tab-content">
                            <el-descriptions :column="2" border class="other-info-descriptions">
                                <el-descriptions-item label="调拨单号" :span="1">
                                    <span class="info-value">{{ transferForm.transferNo || '-' }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="调拨类型" :span="1">
                                    <span class="info-value">{{ transferForm.transferType || '-' }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="制单备注" :span="1">
                                    <span class="info-value">{{ transferForm.remark || '-' }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="经办人" :span="1">
                                    <span class="info-value">{{ transferForm.handler || '-' }}</span>
                                </el-descriptions-item>
                            </el-descriptions>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="调拨明细" name="details">
                        <div class="tab-content">
                            <el-button type="primary" size="small" @click="handleExport" style="margin-bottom: 12px">导出</el-button>
                            <el-table :data="transferDetails" border stripe style="width: 100%" v-loading="detailLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
                                <el-table-column prop="productCode" label="货品编号" min-width="140" show-overflow-tooltip />
                                <el-table-column label="规格型号" min-width="120" show-overflow-tooltip>
                                    <template #default="{ row }">
                                        {{ row.specificationModel || row.productUnit || '--' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="unitName" label="单位" min-width="100" show-overflow-tooltip />
                                <el-table-column prop="productTypeName" label="货品类型" min-width="120" show-overflow-tooltip />
                                <el-table-column prop="outboundCurrentStock" label="调出仓当前库存" width="140" align="right">
                                    <template #default="{ row }">
                                        {{ row.outboundCurrentStock ?? 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="inboundCurrentStock" label="调入仓当前库存" width="140" align="right">
                                    <template #default="{ row }">
                                        {{ row.inboundCurrentStock ?? 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="调拨数量" width="120" align="right">
                                    <template #default="{ row }">
                                        {{ row.transferQuantity ?? 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="调拨单价" width="120" align="right">
                                    <template #default="{ row }">
                                        ¥{{ Number(row.transferUnitPrice ?? 0).toFixed(2) }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="调拨金额" width="120" align="right">
                                    <template #default="{ row }">
                                        <span class="amount-text">¥{{ Number(row.transferAmount ?? 0).toFixed(2) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip>
                                    <template #default="{ row }">
                                        {{ row.remark || '--' }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="detail-summary" v-if="transferDetails.length > 0">
                                <span>调拨种类：{{ transferDetails.length }}</span>
                                <span>调拨数量：{{ totalQuantity }}</span>
                                <span>总金额：<span class="amount-text">¥{{ totalAmount.toFixed(2) }}</span></span>
                            </div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="出库记录" name="outbound">
                        <div class="tab-content">
                            <el-table :data="outboundRecords" border stripe style="width: 100%" v-loading="outboundLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="outboundNo" label="出库单号" min-width="160" show-overflow-tooltip />
                                <el-table-column prop="outboundDate" label="出库日期" width="140">
                                    <template #default="{ row }">
                                        {{ formatDate(row.outboundDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
                                <el-table-column prop="quantity" label="出库数量" width="120" align="right" />
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                            </el-table>
                            <div v-if="outboundRecords.length === 0" class="empty-text">暂无出库记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="入库记录" name="inbound">
                        <div class="tab-content">
                            <el-table :data="inboundRecords" border stripe style="width: 100%" v-loading="inboundLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="inboundNo" label="入库单号" min-width="160" show-overflow-tooltip />
                                <el-table-column prop="inboundDate" label="入库日期" width="140">
                                    <template #default="{ row }">
                                        {{ formatDate(row.inboundDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
                                <el-table-column prop="quantity" label="入库数量" width="120" align="right" />
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                            </el-table>
                            <div v-if="inboundRecords.length === 0" class="empty-text">暂无入库记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="操作记录" name="operation">
                        <div class="tab-content">
                            <el-table :data="operationRecords" border stripe style="width: 100%" v-loading="operationLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="operationType" label="操作类型" width="120" />
                                <el-table-column prop="operationTime" label="操作时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.operationTime) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                                <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
                            </el-table>
                            <div v-if="operationRecords.length === 0" class="empty-text">暂无操作记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="审核记录" name="approval">
                        <div class="tab-content">
                            <el-table :data="approvalRecords" border stripe style="width: 100%" v-loading="approvalLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="approvalStatus" label="审核状态" width="120">
                                    <template #default="{ row }">
                                        <el-tag :type="row.approvalStatus === '通过' ? 'success' : 'danger'" size="small">
                                            {{ row.approvalStatus }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="approvalTime" label="审核时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.approvalTime) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="approver" label="审核人" width="100" show-overflow-tooltip />
                                <el-table-column prop="remark" label="审核意见" min-width="200" show-overflow-tooltip />
                            </el-table>
                            <div v-if="approvalRecords.length === 0" class="empty-text">暂无审核记录</div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

const route = useRoute()
const router = useRouter()

const transferForm = reactive({
    transferId: '',
    transferNo: '',
    transferStatus: 0,
    transferApplicationDate: '',
    transferType: '',
    outboundWarehouseId: '',
    outboundWarehouseName: '',
    inboundWarehouseId: '',
    inboundWarehouseName: '',
    outboundStatus: 0,
    inboundStatus: 0,
    outboundQuantity: 0,
    inboundQuantity: 0,
    transferQuantity: 0,
    handler: '',
    maker: '',
    department: '',
    makerTime: '',
    remark: '',
})

const transferDetails = ref<any[]>([])
const detailLoading = ref(false)

const activeTab = ref('other')

const outboundRecords = ref<any[]>([])
const inboundRecords = ref<any[]>([])
const operationRecords = ref<any[]>([])
const approvalRecords = ref<any[]>([])
const outboundLoading = ref(false)
const inboundLoading = ref(false)
const operationLoading = ref(false)
const approvalLoading = ref(false)

const totalQuantity = computed(() => {
    return transferDetails.value.reduce((sum, item) => sum + (item.transferQuantity || 0), 0)
})

const totalAmount = computed(() => {
    return transferDetails.value.reduce((sum, item) => sum + (item.transferAmount || 0), 0)
})

const getStatusText = (status: number) => {
    switch (status) {
        case 0:
            return '草稿'
        case 1:
            return '待审核'
        case 2:
            return '驳回'
        case 3:
            return '通过'
        case 4:
            return '已完成'
        default:
            return '未知'
    }
}

const getStatusTagType = (status: number) => {
    switch (status) {
        case 3:
        case 4:
            return 'success'
        case 1:
            return 'warning'
        case 2:
            return 'danger'
        default:
            return 'info'
    }
}

const getOutboundStatusText = (status?: number) => {
    switch (status) {
        case 0:
            return '未出库'
        case 1:
            return '部分出库'
        case 2:
            return '已出库'
        default:
            return '——'
    }
}

const getOutboundStatusTagType = (status?: number) => {
    switch (status) {
        case 0:
            return 'info'
        case 1:
            return 'warning'
        case 2:
            return 'success'
        default:
            return 'info'
    }
}

const getInboundStatusText = (status?: number) => {
    switch (status) {
        case 0:
            return '未入库'
        case 1:
            return '部分入库'
        case 2:
            return '已入库'
        default:
            return '——'
    }
}

const getInboundStatusTagType = (status?: number) => {
    switch (status) {
        case 0:
            return 'info'
        case 1:
            return 'warning'
        case 2:
            return 'success'
        default:
            return 'info'
    }
}

const formatDate = (date?: string) => {
    if (!date) return '--'
    return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
    if (!date) return '--'
    return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

const handleClose = () => {
    router.push('/GetTransfer')
}

const handleTransferOut = () => {
    ElMessage.info('调出功能待实现')
}

const handleCopy = () => {
    router.push({
        path: '/CreateTransfer',
        query: { copyFrom: transferForm.transferId },
    })
}

const handlePrint = () => {
    ElMessage.info('打印功能待实现')
}

const handleExport = () => {
    ElMessage.info('导出功能待实现')
}

const handleTabChange = (tab: string) => {
    if (tab === 'outbound' && outboundRecords.value.length === 0) {
        loadOutboundRecords()
    } else if (tab === 'inbound' && inboundRecords.value.length === 0) {
        loadInboundRecords()
    } else if (tab === 'operation' && operationRecords.value.length === 0) {
        loadOperationRecords()
    } else if (tab === 'approval' && approvalRecords.value.length === 0) {
        loadApprovalRecords()
    }
}

const loadOutboundRecords = async () => {
    outboundLoading.value = true
    try {
        const res = await myaxios.get('/api/Transfer/GetOutboundRecords', {
            params: { transferId: transferForm.transferId },
        })
        if (res.data?.code === 200) {
            outboundRecords.value = res.data.data || []
        }
    } catch (error) {
        console.error('获取出库记录失败:', error)
    } finally {
        outboundLoading.value = false
    }
}

const loadInboundRecords = async () => {
    inboundLoading.value = true
    try {
        const res = await myaxios.get('/api/Transfer/GetInboundRecords', {
            params: { transferId: transferForm.transferId },
        })
        if (res.data?.code === 200) {
            inboundRecords.value = res.data.data || []
        }
    } catch (error) {
        console.error('获取入库记录失败:', error)
    } finally {
        inboundLoading.value = false
    }
}

const loadOperationRecords = async () => {
    operationLoading.value = true
    try {
        const res = await myaxios.get('/api/Transfer/GetOperationRecords', {
            params: { transferId: transferForm.transferId },
        })
        if (res.data?.code === 200) {
            operationRecords.value = res.data.data || []
        }
    } catch (error) {
        console.error('获取操作记录失败:', error)
    } finally {
        operationLoading.value = false
    }
}

const loadApprovalRecords = async () => {
    approvalLoading.value = true
    try {
        const res = await myaxios.get('/api/Transfer/GetApprovalRecords', {
            params: { transferId: transferForm.transferId },
        })
        if (res.data?.code === 200) {
            approvalRecords.value = res.data.data || []
        }
    } catch (error) {
        console.error('获取审核记录失败:', error)
    } finally {
        approvalLoading.value = false
    }
}

const loadTransferDetail = async (id: string | number) => {
    if (!id) return
    detailLoading.value = true
    try {
        const cached = sessionStorage.getItem('TRANSFER_DETAIL_CACHE')
        if (cached) {
            try {
                const cachedData = JSON.parse(cached)
                Object.assign(transferForm, cachedData)
                sessionStorage.removeItem('TRANSFER_DETAIL_CACHE')
            } catch (e) {
                console.warn('解析缓存数据失败:', e)
            }
        }

        const res = await myaxios.get('/api/Transfer/GetTransferDetail', {
            params: { transferId: id },
        })

        if (res.data?.code === 200) {
            const data = res.data.data || {}
            Object.assign(transferForm, {
                transferId: data.transferId || id,
                transferNo: data.transferNo || '',
                transferStatus: data.transferStatus ?? 0,
                transferApplicationDate: data.transferApplicationDate || '',
                transferType: data.transferType || '',
                outboundWarehouseId: data.outboundWarehouseId || '',
                outboundWarehouseName: data.outboundWarehouseName || '',
                inboundWarehouseId: data.inboundWarehouseId || '',
                inboundWarehouseName: data.inboundWarehouseName || '',
                outboundStatus: data.outboundStatus ?? 0,
                inboundStatus: data.inboundStatus ?? 0,
                outboundQuantity: data.outboundQuantity ?? 0,
                inboundQuantity: data.inboundQuantity ?? 0,
                transferQuantity: data.transferQuantity ?? 0,
                handler: data.handler || '',
                maker: data.maker || data.makerName || '',
                department: data.department || data.organizationName || '',
                makerTime: data.makerTime || data.createdTime || '',
                remark: data.remark || '',
            })

            const details = data.transferDetails || data.details || []
            transferDetails.value = details.map((item: any) => ({
                productId: item.productId || '',
                productName: item.productName || '',
                productCode: item.productCode || '',
                specificationModel: item.specificationModel || item.productUnit || '',
                productUnit: item.productUnit || '',
                unitName: item.unitName || item.unit || '',
                productTypeName: item.productTypeName || '',
                outboundCurrentStock: item.outboundCurrentStock ?? 0,
                inboundCurrentStock: item.inboundCurrentStock ?? 0,
                transferQuantity: item.transferQuantity || 0,
                transferUnitPrice: item.transferUnitPrice || 0,
                transferAmount: item.transferAmount || 0,
                remark: item.remark || '',
            }))
        }
    } catch (error) {
        console.error('获取调拨单详情失败:', error)
        ElMessage.error('获取调拨单详情失败')
    } finally {
        detailLoading.value = false
    }
}

onMounted(() => {
    const transferId = route.query.transferId as string
    if (transferId) {
        loadTransferDetail(transferId)
    }
})
</script>

<style scoped>
.detail-page {
    padding: 20px;
}

.detail-header {
    margin-bottom: 16px;
}

.detail-card {
    margin-bottom: 16px;
}

.header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.title-area {
    display: flex;
    align-items: center;
    gap: 12px;
}

.order-label {
    font-size: 16px;
    font-weight: 600;
}

.order-number {
    font-size: 18px;
    font-weight: 600;
    color: #1677ff;
}

.status-tag {
    margin-left: 8px;
}

.status-info {
    display: flex;
    gap: 24px;
    margin-bottom: 16px;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;
}

.status-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-label {
    font-size: 14px;
    color: #606266;
}

.status-count {
    font-size: 14px;
    color: #909399;
}

.info-content {
    margin-top: 16px;
}

.info-value {
    color: #303133;
}

.tabs-section {
    margin-top: 16px;
}

.tab-content {
    padding: 16px 0;
}

.detail-summary {
    margin-top: 12px;
    display: flex;
    gap: 24px;
    font-size: 14px;
    color: #606266;
}

.amount-text {
    color: #ff5722;
    font-weight: 600;
}

.empty-text {
    text-align: center;
    padding: 40px;
    color: #909399;
}

.action-buttons {
    display: flex;
    gap: 8px;
}
</style>

